package com.hjy.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.hjy.common.myenum.CodeEnum;
import com.hjy.common.utils.R;
import com.hjy.compoent.MessageComponent;
import com.hjy.constan.RedisConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

// Short Message Service
@RestController
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private MessageComponent messageComponent;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        // 1, 首先判断是否在 60 秒内重复发送
        String redisCode = stringRedisTemplate.opsForValue().get(RedisConst.REDIS_CODE_PREFIX + phone);
        // 非空, 判断是否是 60 内重复发送
        if (StrUtil.isNotBlank(redisCode)) {
            Long redisTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - redisTime < 60000) {
                // 说明时间在 60 秒内, 不予理会
                return R.error(CodeEnum.REDIS_RESPONSE_1.getCode(),CodeEnum.REDIS_RESPONSE_1.getMsg());
            }
        }

        String code = RandomUtil.randomNumbers(6);
        // 设置进redis
        // 有效期 10 分钟
        stringRedisTemplate.opsForValue().set(RedisConst.REDIS_CODE_PREFIX + phone,code + "_" + System.currentTimeMillis(),10, TimeUnit.MINUTES);
        messageComponent.sendMessage(phone,code);
        return R.ok();
    }
}
